package com.cgy.utils.netx.ftp.server;

import com.cgy.utils.netx.config.ServerConfig;
import com.cgy.utils.netx.server.INetworkServerLibrary;
import com.google.common.base.Preconditions;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CHTK
 */
public class FtpServer implements INetworkServerLibrary<org.apache.ftpserver.FtpServer> {

    private org.apache.ftpserver.FtpServer server;

    @Override
    public INetworkServerLibrary<org.apache.ftpserver.FtpServer> config(ServerConfig serverConfig) {
        Preconditions.checkArgument(null != serverConfig);
        Preconditions.checkArgument(serverConfig.getPort() > 0);

        FtpServerFactory serverFactory = new FtpServerFactory();

        ListenerFactory factory = new ListenerFactory();
        //设置监听端口
        factory.setPort(serverConfig.getPort());

        //替换默认监听
        serverFactory.addListener("default", factory.createListener());

        BaseUser user = new BaseUser();
        user.setName(serverConfig.getUsername());
        user.setPassword(serverConfig.getPassword());
        user.setHomeDirectory(serverConfig.getPath());

        List<Authority> authorities = new ArrayList<Authority>();
        //增加写权限
        authorities.add(new WritePermission());
        user.setAuthorities(authorities);

        //增加该用户
        try {
            serverFactory.getUserManager().save(user);
        } catch (FtpException e) {
            e.printStackTrace();
        }

        /**
         * 也可以使用配置文件来管理用户
         */
//	    PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
//	    userManagerFactory.setFile(new File("users.properties"));
//	    serverFactory.setUserManager(userManagerFactory.createUserManager());
        this.server = serverFactory.createServer();
        return this;
    }

    @Override
    public void start() throws Exception {
        server.start();
    }

    @Override
    public void stop() throws Exception {
        server.stop();
    }

    @Override
    public org.apache.ftpserver.FtpServer getServer() throws Exception {
        return server;
    }
}
